<template>
  <div class="container">
    <div class="card">
      <div class="breadcrumb">
        <el-button @click="goBack" type="text">
          <el-icon>
            <Back />
          </el-icon>
          返回
        </el-button>
      </div>

      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else class="preview-container">
        <h2 class="preview-title">{{ metadata.nickname || fileName }}</h2>

        <!-- 视频预览 -->
        <template v-if="fileType === 'video'">
          <div class="video-container">
            <video v-if="fileUrl" controls class="video-player">
              <source :src="fileUrl" :type="videoType">
              您的浏览器不支持视频播放
            </video>
          </div>
        </template>

        <!-- 图片预览 -->
        <template v-else-if="fileType === 'image'">
          <div class="image-container">
            <img v-if="fileUrl" :src="fileUrl" class="image-preview" alt="图片预览">
          </div>
        </template>

        <!-- 其他文件 -->
        <template v-else>
          <div class="file-container">
            <el-icon class="file-icon">
              <Document />
            </el-icon>
            <p>此文件类型不支持预览</p>
            <el-button type="primary" @click="downloadFile" class="mt-20">
              <el-icon>
                <Download />
              </el-icon>
              下载文件
            </el-button>
          </div>
        </template>

        <div class="file-info">
          <h3>文件信息</h3>
          <p><strong>文件名:</strong> {{ fileName }}</p>
          <p v-if="metadata.nickname"><strong>昵称:</strong> {{ metadata.nickname }}</p>
          <p><strong>类型:</strong> {{ fileType }}</p>
          <p><strong>路径:</strong> {{ decodeURIComponent(route.params.key) }}</p>
        </div>

        <div class="file-actions">
          <el-button type="primary" @click="editMetadata">
            <el-icon>
              <Edit />
            </el-icon>
            编辑元数据
          </el-button>
          <el-button @click="downloadFile">
            <el-icon>
              <Download />
            </el-icon>
            下载
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <!-- 编辑元数据对话框 -->
  <el-dialog v-model="dialogVisible" title="编辑元数据" width="500px">
    <el-form :model="editForm" label-width="100px">
      <el-form-item label="名称">
        <el-input v-model="editForm.nickname" placeholder="请输入自定义名称" />
      </el-form-item>

      <el-form-item label="缩略图">
        <el-upload class="thumbnail-uploader" action="#" :http-request="uploadThumbnail" :show-file-list="false"
          :before-upload="beforeThumbnailUpload">
          <img v-if="thumbnailPreview" :src="thumbnailPreview" class="thumbnail-preview" />
          <el-icon v-else class="thumbnail-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="el-upload__tip">
          请上传图片作为缩略图
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMetadata" :loading="saving">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Back, Document, Download, Edit, Plus } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const fileUrl = ref('')
const metadata = ref({})

// 编辑对话框
const dialogVisible = ref(false)
const editForm = ref({
  id: null,
  cosKey: '',
  nickname: '',
  type: ''
})
const thumbnailPreview = ref('')
const thumbnailFile = ref(null)
const saving = ref(false)

// 计算文件名
const fileName = computed(() => {
  const key = decodeURIComponent(route.params.key)
  return key.split('/').pop()
})

// 计算文件类型
const fileType = computed(() => {
  const name = fileName.value.toLowerCase()
  if (/\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(name)) {
    return 'video'
  } else if (/\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(name)) {
    return 'image'
  } else {
    return 'file'
  }
})

// 计算视频MIME类型
const videoType = computed(() => {
  const name = fileName.value.toLowerCase()
  if (name.endsWith('.mp4')) return 'video/mp4'
  if (name.endsWith('.webm')) return 'video/webm'
  if (name.endsWith('.ogg')) return 'video/ogg'
  return 'video/mp4' // 默认
})

// 获取文件URL
const fetchFileUrl = async () => {
  try {
    const key = route.params.key
    const response = await axios.get(`/api/cos/url/${key}`)

    if (response.data.success) {
      fileUrl.value = response.data.url
    } else {
      ElMessage.error('获取文件URL失败')
    }
  } catch (error) {
    console.error('获取文件URL失败:', error)
    ElMessage.error('获取文件URL失败')
  }
}

// 获取文件元数据
const fetchMetadata = async () => {
  try {
    const key = decodeURIComponent(route.params.key)
    const response = await axios.get(`/api/metadata/${encodeURIComponent(key)}`)

    if (response.data.success) {
      metadata.value = response.data.data
    }
  } catch (error) {
    console.error('获取元数据失败:', error)
    // 如果没有元数据，不显示错误
    metadata.value = {}
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 下载文件
const downloadFile = () => {
  if (fileUrl.value) {
    const a = document.createElement('a')
    a.href = fileUrl.value
    a.download = fileName.value
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  } else {
    ElMessage.error('文件URL不可用')
  }
}

// 编辑元数据
const editMetadata = () => {
  const key = decodeURIComponent(route.params.key)

  // 检查是否是缩略图文件夹内的文件
  const isThumbnailFile = key.includes('/thumbnail/') || key.startsWith('thumbnail/')

  editForm.value = {
    id: metadata.value.id,
    cosKey: key,
    nickname: metadata.value.nickname || fileName.value,
    type: fileType.value
  }
  thumbnailPreview.value = metadata.value.thumbnailUrl || ''

  // 如果是缩略图文件夹内的图片，显示警告
  if (isThumbnailFile && fileType.value === 'image') {
    ElMessage({
      message: '注意：不建议为缩略图文件夹内的图片设置缩略图，这可能导致无限循环',
      type: 'warning',
      duration: 5000
    })
  }

  dialogVisible.value = true
}

// 缩略图上传前验证
const beforeThumbnailUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('缩略图必须是图片格式!')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('缩略图大小不能超过 2MB!')
    return false
  }

  thumbnailFile.value = file

  // 预览缩略图
  const reader = new FileReader()
  reader.onload = (e) => {
    thumbnailPreview.value = e.target.result
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

// 自定义上传方法
const uploadThumbnail = () => {
  // 这里不做任何事情，因为我们在保存时一起上传
}

// 保存元数据
const saveMetadata = async () => {
  saving.value = true
  try {
    // 检查是否是缩略图文件夹内的项目
    const isThumbnailItem = editForm.value.cosKey.includes('/thumbnail/') ||
      editForm.value.cosKey.startsWith('thumbnail/')

    // 如果要为缩略图文件夹内的图片上传缩略图，显示警告并拒绝
    if (isThumbnailItem && thumbnailFile.value && fileType.value === 'image') {
      ElMessage.error('不能为缩略图文件夹内的图片设置缩略图，这会导致无限循环')
      saving.value = false
      return
    }

    const formData = new FormData()
    formData.append('cosKey', editForm.value.cosKey)
    formData.append('nickname', editForm.value.nickname)
    formData.append('type', editForm.value.type)

    if (thumbnailFile.value) {
      formData.append('thumbnail', thumbnailFile.value, 'thumbnail.png')
    }

    const response = await axios.post('/api/metadata/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.success) {
      ElMessage.success('元数据更新成功')
      dialogVisible.value = false
      // 刷新元数据
      await fetchMetadata()
      // 刷新缩略图
      if (response.data.data.thumbnailUrl) {
        // 使用COS URL，我们需要重新获取
        await fetchThumbnailUrl()
      }
    } else {
      ElMessage.error(response.data.message || '元数据更新失败')
    }
  } catch (error) {
    console.error('保存元数据失败:', error)
    ElMessage.error('保存元数据失败')
  } finally {
    saving.value = false
  }
}

// 获取缩略图URL
const fetchThumbnailUrl = async () => {
  if (metadata.value && metadata.value.thumbnailUrl) {
    try {
      console.log('获取缩略图URL:', metadata.value.thumbnailUrl);
      const response = await axios.get(`/api/cos/url/${encodeURIComponent(metadata.value.thumbnailUrl)}`);
      if (response.data.success) {
        console.log('缩略图URL获取成功:', response.data.url);
        thumbnailPreview.value = response.data.url;
      } else {
        console.error('获取缩略图URL失败:', response.data);
      }
    } catch (error) {
      console.error('获取缩略图URL失败:', error);
    }
  } else if (fileType.value === 'image') {
    // 如果是图片但没有缩略图，尝试获取或生成
    try {
      const response = await axios.get(`/api/cos/thumbnail/${encodeURIComponent(route.params.key)}`);
      if (response.data.success && response.data.thumbnailUrl) {
        console.log('成功获取新的缩略图URL:', response.data.thumbnailUrl);
        thumbnailPreview.value = response.data.thumbnailUrl;
      }
    } catch (error) {
      console.error('请求生成缩略图失败:', error);
    }
  } else {
    console.log('没有缩略图URL可获取');
  }
}

onMounted(async () => {
  console.log('预览组件加载，文件路径:', route.params.key);
  await fetchFileUrl();
  await fetchMetadata();
  console.log('获取到的元数据:', metadata.value);
  await fetchThumbnailUrl();
})
</script>

<style scoped>
.preview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-title {
  margin-bottom: 20px;
  text-align: center;
}

.video-container,
.image-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.video-player {
  max-width: 100%;
  max-height: 70vh;
}

.image-preview {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.file-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.file-icon {
  font-size: 64px;
  color: #909399;
  margin-bottom: 20px;
}

.file-info {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.file-info h3 {
  margin-bottom: 10px;
}

.file-info p {
  margin-bottom: 5px;
}

.file-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.thumbnail-uploader {
  width: 120px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.thumbnail-uploader:hover {
  border-color: #409EFF;
}

.thumbnail-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.thumbnail-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>